#include <MAUtil/Moblet.h>
#include <MAUtil/Connection.h>
#include <maapi.h>
#include <mastdlib.h>
#include <maprofile.h>
#include <mastring.h>

using namespace MAUtil;

#define BSIZE 1024
#define SERVER_ADDRESS "http://localhost:8081"

class TalkToServer : private HttpConnectionListener {
private:

	HttpConnection m_http;
	char buff[BSIZE];

	static TalkToServer* m_singleton;


	TalkToServer() : m_http(this){}

public:
	static TalkToServer* getInstance(){
		if(m_singleton == NULL)
			m_singleton = new TalkToServer();
		return m_singleton;
	}

	void SendMessage(const char* message){
		m_http.close();

		int bufferLen = strlen(SERVER_ADDRESS) + strlen(message);

		char* buffer = new char[bufferLen];
		strcat(buffer, SERVER_ADDRESS);
		strcat(buffer, message);

		int result = m_http.create(buffer, HTTP_GET);

		delete buffer;

		if(result<0){
			printf("http.create failed %i\n", result);
		}else{
			m_http.finish();
		}
	}

	virtual void httpFinished(HttpConnection* http, int result) {
		printf("httpFinished result: %i\n", result);

		if (result <=0) return;

		String line;

		result = m_http.getResponseHeader("content-length", &line);

		if(result < 0){
			m_http.recv(buff, BSIZE);
		}
		if (result > 0) {
			printf("content-length: &s bytes\n", line.c_str());
			int length = atoi(line.c_str());
			if (length >= BSIZE) {
				printf("Buffer to small.");
				length = BSIZE - 1;
			}
			buff[length] = 0;
			m_http.read(buff, length);
			printf("read into buffer:\n%s\n", buff);

			if (true) {
				m_http.read(buff, length);
				printf("read into buffer:\n%s\n", buff);
			}

		} else {
			printf("No content-length\n");
			m_http.recv(buff, BSIZE);
			printf(buff);
		}
	}

	virtual void connEvent(const MAConnEventData& data) {}

	virtual void connWriteFinished(Connection *conn, int result) {}

	virtual void connRecvFinished(Connection *conn, int result) {}
	virtual void connReadFinished(Connection *conn, int result) {}
};

TalkToServer* TalkToServer::m_singleton;
